/*
 * @Author: chengsl
 * @Date: 2023-05-09 18:04:53
 * @LastEditors: chengsl
 * @LastEditTime: 2023-05-10 16:06:22
 * @Description: qiankun需要的路由
 */
import { asyncRouterTable, loadView } from './index'

// asyncRouterTable ：项目的路由表
const routerList = JSON.parse(JSON.stringify(asyncRouterTable))

/**
 * @description: 递归路由表，收集暴露的 qiankun 路由
 * @param {Array} routers
 */
function filterQiankunRouter(routers) {
  let result = []
  for (const router of routers) {
    if (router.qiankunRouter) { // 收集暴露的 qiankun 路由
      result.push({
        name: router.name,
        path: '/' + router.name,
        hidden: router.hidden, // 是否显示用配置的
        component: router.component || router.iframeComponent,
        meta: {
          title: router.meta.title,
          icon: router.meta.icon
        }
      })
    }
    if (router.children && router.children.length) {
      const tempResult = filterQiankunRouter(router.children)
      result = [...result, ...tempResult]
    }
  }
  return result
}

const qiankunRoutes = filterQiankunRouter(routerList)

/* 过滤收集的 qiankun 路由，懒加载路由对应的组件 */
for (const router of qiankunRoutes) {
  const component = router.component
  router.component = loadView(component)
}

// 导出微应用系统目暴露到 qiankun主项目的路由表
export { qiankunRoutes }

/**
 * @description: qiankun环境下注册的路由守卫
 * @param {*} qiankunRouter qiankunRouter
 */
export function asyncQiankunRouters(qiankunRouter) {
  qiankunRouter.beforeEach(async(to, from, next) => {
    // console.log('qiankun环境下的路由守卫')
    next()
  })
}
